package org.qpcr.community.project.web.excel;

import lombok.Getter;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.validator.ValidatorUtils;
import org.qpcr.community.io.excel.AbstractImporter;
import org.qpcr.community.io.excel.ImportHelper;
import org.qpcr.community.io.file.FileManager;
import org.qpcr.community.project.model.entity.TestSequenceInstanceEntity;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 检测项导入.
 *
 * @author yanss 2024/6/13
 * @since 2.1
 */
public class TestSequenceExcelImporter extends AbstractImporter<TestSequenceExcelInfo> {

    @Getter
    private final List<TestSequenceInstanceEntity> testSequenceInstanceList;

    private final Authentication auth;

    public TestSequenceExcelImporter(FileManager fileManager,
                                     WebClient client,
                                     List<TestSequenceInstanceEntity> testSequenceInstanceList,
                                     Authentication auth) {
        super(fileManager, client);
        this.testSequenceInstanceList = testSequenceInstanceList;
        this.auth = auth;
    }

    @Override
    protected Mono<Void> handleData(Flux<TestSequenceExcelInfo> data) {
        return data
            .doOnNext(ValidatorUtils::tryValidate)
            .map(testSequenceExcelInfo -> testSequenceExcelInfo.initTestSequenceInstance(testSequenceInstanceList, auth))
            .then();
    }

    @Override
    protected TestSequenceExcelInfo newInstance() {
        return new TestSequenceExcelInfo();
    }

    @Override
    protected void customImport(ImportHelper<TestSequenceExcelInfo> helper) {
        helper.fallbackSingle(true);
    }
}
